<?php

namespace App\Model\Admin;

use App\Model\Distributors;
use App\Model\Json;
use DateTimeZone;
use Hyperf\HttpServer\Contract\RequestInterface;
use Phper666\JWTAuth\Util\JWTUtil;
use Psr\Container\NotFoundExceptionInterface;
use RedisException;
use Psr\Container\ContainerExceptionInterface;
use App\Model\Model;

class Admin extends Model
{

    public bool $timestamps = true;

    protected ?string $table = 'admin';

    const TYPE_ADMIN = 1;
    const TYPE_NORMAL = 2;
    const TYPE_USER = 3;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected array $guarded = [];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected array $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'station_class' => Json::class
    ];

    /**构造登陆态内容
     * @param $info
     * @return array
     */
    public function makeInfo($info): array
    {
        $user = [];
        $user['uid'] = $info->id;
        $user['id'] = $info->id;
        $user['name'] = $info->name;
        $user['mobile'] = $info->mobile;
        $user['type'] = $info->type;
        if($user['type'] == self::TYPE_USER){
            $user['distributor_id'] = Distributors::where('mobile',$info->mobile)->value('id');
        }
        return $user;
    }

    /**获取登陆态
     * @param RequestInterface $request
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|RedisException
     */
    public function getInfo(RequestInterface $request,): array
    {
        $token = $request->getHeaderLine('Token');
        if ($token) {
            $jwtArray = JWTUtil::getUserData("Bearer ".$token);
            if (!isset($jwtArray['id'])) {
                return [];
            }
            $jwtArray['now'] = date('Y-m-d H:i:s', time());
            if ($jwtArray) {
                $jwtArray['exp'] = $jwtArray['exp']->setTimezone(new DateTimeZone('Asia/Shanghai'));
                $jwtArray['exp_time'] = $jwtArray['exp']->getTimestamp();
                if (time() > $jwtArray['exp_time']) {
                    return [];
                }
            }
            return $jwtArray;
        }
        return [];
    }
}
